package com.feilong.modules.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.feilong.modules.common.exception.APIException;
import com.feilong.modules.model.user.constant.UserInfoConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成token的工具类
 */
@Slf4j
public class TokenUtil {

    /**
     * 设置过期时间为两小时
     */
    public static final Long EXPIRE_TIME = 7200000L;

    /**
     * token秘钥
     */
    private static final String TOKEN_SECRET = "ZCEQIUBFKSJBFFL2021BQWE";

    /**
     * 生成token
     * @param account
     * @param password
     * @return
     */
    public static String generateToken(String account, String password){
        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息T
            Map<String,Object> header = new HashMap<>();
            header.put("typ","JWT");
            header.put("alg","HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("account", account)
                    .withClaim("password",password).withExpiresAt(date)
                    .sign(algorithm);
            log.info("账号 -> {} 生成token -> {}", account, token);
            if (StringUtils.isBlank(token)) {
                // 生成token失败
                log.error("账号 -> {} 生成token为空", account);
                throw new APIException(UserInfoConstant.LOGIN_FAIL);
            }
        }catch (Exception e){
            log.error("Token工具类生成token失败，失败异常 -> {}", e.toString());
        }
        return token;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static String verifyToken(String token){
        String account = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            account = jwt.getClaim("account").asString();
            if (StringUtils.isBlank(account)) {
                throw new APIException(UserInfoConstant.INVALID_TOKEN);
            }
            log.info("账号 -> {} 校验token", account);
        } catch (Exception e){
            log.error("Token工具类校验token失败，失败异常 -> {}", e.toString());
        }
        return account;
    }

}
